package connection;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import business.BusinessVideo;

public class ConnectionManager {

	private Driver dBDriver = null;
	private static Connection conn = null;
	private static ConnectionManager cm;
	private static Properties prop=new Properties();
	
	
	/**
	 * load driver
	 */
	private ConnectionManager(){
		try {
			prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			dBDriver = (Driver) Class.forName(prop.getProperty("drivername")).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			DriverManager.registerDriver(dBDriver);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * If there is not a ConnectionManager instance, create one.
	 * If yes, then return the instance.
	 */
	public static synchronized ConnectionManager getInstance() {
		if (cm==null){
			cm = new ConnectionManager();
		}
		return cm;
	}
	/**
	 * open one connection with the database
	 */
	public Connection openConnection(){
		try {
			conn = DriverManager.getConnection("jdbc:relique:csv:"+prop.getProperty("rutacsv"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * close connection with the database
	 */
	public void closeConnection(){
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * unregister the driver
	 */
	public void unregisterDriver(){
		try {
			DriverManager.deregisterDriver(dBDriver);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main (String [] args)
	{   
		System.out.println("====TODOS LOS VIDEOS====");
		System.out.println(BusinessVideo.getAllVideos());
		System.out.println("\n\n====TODOS LOS VIDEOS SEGUN UN GENERO====");
		System.out.println(BusinessVideo.getAllVideosByGenre("Ficcion"));
		System.out.println("\n\n====TODOS LOS VIDEOS QUE EMPIEZAN POR UNA LETRA====");
		System.out.println(BusinessVideo.getAllVideosStartingWithLetter('a'));
		System.out.println("\n\n====VIDEO CON UN TITULO DADO====");
		System.out.println(BusinessVideo.getVideoByTitle("avenger"));
	}
}
